package com.coy.web.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.extension.api.R;
import com.coy.web.common.consts.WebConsts;
import com.coy.web.common.dto.DataResult;
import com.coy.web.common.exception.BizResultCode;
import com.coy.web.config.SmsTemplateProperties;
import com.coy.web.dao.service.IUserInfoService;
import com.coy.web.feign.dto.SmsReq;
import com.coy.web.service.ISmsService;
import com.coy.web.sms.AliyunSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.security.util.SecurityConstants;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author chenck
 * @date 2021/6/13 21:43
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    @Resource
    SmsTemplateProperties smsTemplateProperties;

    @Resource
    AliyunSmsUtils smsUtils;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    IUserInfoService userInfoService;

    @Override
    public DataResult sendSmsCode(SmsReq req) throws ClientException {
        String signName = null;
        String templateCode = null;
        if (WebConsts.SMS_CODE_LOGIN.equals(req.getType())) {// 登录
            signName = smsTemplateProperties.getSignName1();
            templateCode = smsTemplateProperties.getTemplateCode1();
        } else if (WebConsts.SMS_CODE_FORGET_PWD.equals(req.getType())) {// 忘记密码
            signName = smsTemplateProperties.getSignName2();
            templateCode = smsTemplateProperties.getTemplateCode2();
        }

        String key = WebConsts.PREFIX_SMS_CODE_DEFAULT + ":" + req.getPhone();
        Long seconds = redisTemplate.opsForValue().getOperations().getExpire(key);

        if (seconds > 240) {
            log.info("验证码发送过频繁:{}", req.getPhone());
            return DataResult.error(BizResultCode.ERR_SEND_SMS_CODE_FREQUENTLY.getCode(), BizResultCode.ERR_SEND_SMS_CODE_FREQUENTLY.getMsg());
        }

        String code = RandomUtil.randomNumbers(Integer.parseInt(WebConsts.CODE_SIZE));
        log.info("手机号生成验证码成功:{},{}", req.getPhone(), code);
        smsUtils.sendSms(signName, req.getPhone(), templateCode, "{\"code\":\"" + code + "\"}");
        redisTemplate.opsForValue().set(key, code, WebConsts.CODE_TIME, TimeUnit.SECONDS);
        return DataResult.succ();
    }
}
